package com.example.fuwenfrom.wechatxcx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 作者：编程小石头
 * 发送小程序订阅消息
 */
@RestController
public class SendWxMessage {
    public String push (@RequestBody LinkedHashMap<String,String> fuwenlist) throws JSONException {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken(fuwenlist);
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(fuwenlist.get("openid"));
        wxMssVo.setTemplate_id(fuwenlist.get("templateid"));
        wxMssVo.setPage("pages/index");

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("thing1", new TemplateData("小程序入门课程"));
        m.put("time2", new TemplateData("2020-05-17 19:20:13"));
//        m.put("thing6", new TemplateData("杭州浙江大学"));
//        m.put("thing7", new TemplateData("第一章第一节"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }

    public String getAccessToken(@RequestBody LinkedHashMap<String,String> fuwenlist) throws JSONException {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", fuwenlist.get("appid"));  //
        params.put("APPSECRET", fuwenlist.get("appsecret"));
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        return Access_Token;
    }
}